<?php
/*
Plugin Name: Windows Live Writer Ultimate Tag Warrior Tagger
Plugin URI: http://kinrowan.net/wordpress/WLW_UTW_Tags
Description: Allows Windows Live Writer users to use WLW Keywords to add tags in Ultimate Tag Warrior.  No config needed (yet).
Version: 0.1
Author: Cori Schlegel
Author URI: http://kinrowan.net
License: GNU GPL 2.0
Tags: wordpress ultimate_tag_warrior windows_live_writer tags
*/

	$logging = 1;

	function wlwLog($msg) {
		global $logging;
		if ($logging) {
			$fp = fopen("../xmlrpc.log","a+");
			$date = gmdate("Y-m-d H:i:s ");
			fwrite($fp, "Logged:\n\n".$date.$msg."\n\n");
			fclose($fp);
		}
		return true;
	}


	/* metaweblog.newPost creates a post */
	function WLW_UTW_newPost($args) {

		global $wpdb, $post_default_category;	//, $utw;

		include_once('UltimateTagWarrior/ultimate-tag-warrior-core.php');
		include_once('UltimateTagWarrior/ultimate-tag-warrior-actions.php');
		load_plugin_textdomain('ultimate-tag-warrior', 'wp-content/plugins/UltimateTagWarrior/languages');
		
		$utw = new UltimateTagWarriorCore();
		
		$utw->CheckForInstall();
		
//		$wp_xmlrpc_server = new wp_xmlrpc_server();
		wlwLog('in wlw new post');

		escape($args);

//		$utw = new UltimateTagWarriorCore();

		wlwLog("UTW=" . serialize($utw) );

		$blog_ID = $args[0]; // we will support this in the near future
		$user_login= $args[1];
		$user_pass = $args[2];
		$content_struct = $args[3];
		$publish = $args[4];
		$tags_from_post = explode(",", $content_struct['mt_keywords']);

		wlwLog(serialize($tags_from_post));

		if (!login_pass_ok($user_login, $user_pass)) {
			return $error;
		}

		$user = set_current_user(0, $user_login);
		if ( !current_user_can('publish_posts') )
			return new IXR_Error(401, 'Sorry, you can not post on this weblog or category.');

		$post_author = $user->ID;

		$post_title = $content_struct['title'];
		$post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
		$post_status = $publish ? 'publish' : 'draft';

		$post_excerpt = $content_struct['mt_excerpt'];
		$post_more = $content_struct['mt_text_more'];

		$comment_status = (empty($content_struct['mt_allow_comments'])) ?
			get_settings('default_comment_status')
			: $content_struct['mt_allow_comments'];

		$ping_status = (empty($content_struct['mt_allow_pings'])) ?
			get_settings('default_ping_status')
			: $content_struct['mt_allow_pings'];

		if ($post_more) {
			$post_content = $post_content . "\n<!--more-->\n" . $post_more;
		}

		$to_ping = $content_struct['mt_tb_ping_urls'];

		// Do some timestamp voodoo
		$dateCreatedd = $content_struct['dateCreated'];
		if (!empty($dateCreatedd)) {
			$dateCreated = $dateCreatedd->getIso();
			$post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
			$post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
		} else {
			$post_date = current_time('mysql');
			$post_date_gmt = current_time('mysql', 1);
		}

		$catnames = $content_struct['categories'];
		wlwLog('Post cats: ' . printr($catnames,true));
		$post_category = array();

		if (is_array($catnames)) {
			foreach ($catnames as $cat) {
				$post_category[] = get_cat_ID($cat);
			}
		}

		// We've got all the data -- post it:
		$postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping');

		$post_ID = wp_insert_post($postdata);

		if (!$post_ID) {
			return new IXR_Error(500, 'Sorry, your entry could not be posted. Something wrong happened.');
		}

		$utw->SaveTags( $post_ID, $tags_from_post );
//		wlwLog( serialize($tags_from_post) . " : post-id-" . $post_ID );


		wlwLog("Posted ! ID: $post_ID");

		return strval($post_ID);
	}


	/* metaweblog.editPost ...edits a post */
	function WLW_UTW_editPost($args) {
		wlwLog('in wlw edit post');


		global $wpdb, $post_default_category;	//, $utw;
//		global $wp_xmlrpc_server;

		include_once('UltimateTagWarrior/ultimate-tag-warrior-core.php');
		include_once('UltimateTagWarrior/ultimate-tag-warrior-actions.php');
		load_plugin_textdomain('ultimate-tag-warrior', 'wp-content/plugins/UltimateTagWarrior/languages');

		$utw = new UltimateTagWarriorCore();

		$utw->CheckForInstall();

		escape($args);

//		$utw = new UltimateTagWarriorCore();

		wlwLog("UTW=" . serialize($utw) );

		$post_ID = $args[0];
		$user_login= $args[1];
		$user_pass = $args[2];
		$content_struct = $args[3];
		$publish = $args[4];

		if (!login_pass_ok($user_login, $user_pass)) {
			return $error;
		}

		set_current_user(0, $user_login);
		if ( !current_user_can('edit_post', $post_ID) )
			return new IXR_Error(401, 'Sorry, you can not edit this post.');

		$postdata = wp_get_single_post($post_ID, ARRAY_A);
		extract($postdata);
		escape($postdata);
	
		$post_title = $content_struct['title'];
		$post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
		$catnames = $content_struct['categories'];
	
		$post_category = array();
	
		if (is_array($catnames)) {
			foreach ($catnames as $cat) {
				$post_category[] = get_cat_ID($cat);
			}
		}
	
		$post_excerpt = $content_struct['mt_excerpt'];
		$post_more = $content_struct['mt_text_more'];
		$post_status = $publish ? 'publish' : 'draft';
	
		if ($post_more) {
			$post_content = $post_content . "\n<!--more-->\n" . $post_more;
		}
	
		$to_ping = $content_struct['mt_tb_ping_urls'];
	
		$comment_status = (empty($content_struct['mt_allow_comments'])) ?
			get_settings('default_comment_status')
			: $content_struct['mt_allow_comments'];
	
		$ping_status = (empty($content_struct['mt_allow_pings'])) ?
			get_settings('default_ping_status')
			: $content_struct['mt_allow_pings'];
	
		// Do some timestamp voodoo
		$dateCreatedd = $content_struct['dateCreated'];
		if (!empty($dateCreatedd)) {
			$dateCreated = $dateCreatedd->getIso();
			$post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
			$post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
		} else {
			$post_date = $postdata['post_date'];
			$post_date_gmt = $postdata['post_date_gmt'];
		}
	
		// We've got all the data -- post it:
		$newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping');
	
		$result = wp_update_post($newpost);
		if (!$result) {
			return new IXR_Error(500, 'Sorry, your entry could not be edited. Something wrong happened.');
		}
	
		$tags_from_post = explode(",", $content_struct['mt_keywords']);

		foreach ( $tags_from_post as $tag ) {
			wlwLog( $tag . " : post-id-" . $post_ID );
			$utw->AddTag( $post_ID, $tag );
		}

//		$utw->SaveTags( $post_ID, $tags_from_post );

		wlwLog(serialize($tags_from_post));

		wlwLog("(MW) Edited ! ID: $post_ID");
	
		return true;
	}
	
	function escape(&$array) {
		global $wpdb;

		foreach ($array as $k => $v) {
			if (is_array($v)) {
				escape($array[$k]);
			} else if (is_object($v)) {
				//skip
			} else {
				$array[$k] = $wpdb->escape($v);
			}
		}
	}

	function login_pass_ok($user_login, $user_pass) {
	  if (!user_pass_ok($user_login, $user_pass)) {
	    $error = new IXR_Error(403, 'Bad login/pass combination.');
	    return false;
	  }
	  return true;
	}

	function WLW_UTW_methods( $methodList ) {
		wlwLog( 'methods: ' . serialize( $methodList ) );
		$methodList['metaWeblog.newPost'] = 'WLW_UTW_newPost';
		$methodList['metaWeblog.editPost'] = 'WLW_UTW_editPost';
		wlwLog( 'new methods: ' . serialize( $methodList ) );
		return $methodList;
	}

add_filter('xmlrpc_methods', 'WLW_UTW_methods');


?>